import { PluginContainer } from './../../pluginContainer';
import { ServerContext } from './../index';
import { NextHandleFunction } from "connect";
import {
  isJSRequest,
  cleanUrl,
  isCSSRequest,
  isImportRequest
} from "../../utils";
import createDebug from "debug";
import { transform } from 'esbuild';
import fs from "fs-extra";
const debug = createDebug("dev");
export async function transformRequest(url: string, serverContext: ServerContext) {
  const { pluginContainer, moduleGraph } = serverContext;
  url = cleanUrl(url);
  const resolveResult = await pluginContainer.resolveId(url);
  let mod = await moduleGraph.getModuleByUrl(url);

  let transformResult;
  if (resolveResult?.id) {
    let code = await pluginContainer.load(resolveResult.id);
    if (typeof code === "object" && code !== null) {
      code = code.code;
    }
    mod = await moduleGraph.ensureEntryFromUrl(url);
    
    if (code) {
      transformResult = await pluginContainer.transform(code as string, resolveResult?.id)
    }
  }
  return transformResult
}
export function transformMiddleware(serverContext: ServerContext): NextHandleFunction {
  return async (req, res, next) => {
    if (req.method !== "GET" || !req.url) {
      return next();
    }


    const url = req.url;
    debug("transformMiddleware: %s", url);

    if (isJSRequest(url) || isCSSRequest(url) || isImportRequest(url)) {
      let result = await transformRequest(url, serverContext) as { code: string } | string
      // console.log("result----", result)
      if (!result) {
        return next()
      }
      if (result && typeof result !== "string") {

        result = result.code;
      }

      res.statusCode = 200;
      res.setHeader("Content-Type", "application/javascript");
      // fs.writeFileSync(process.cwd() + "/test.js", result)
      return res.end(result)
    }
    next()
  }
}